package com.tc.activiti.web.workflow;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.tc.activiti.util.PageUtil;
import com.tc.base.constants.PageConstants;
import com.tc.base.constants.StateEnum;
import com.tc.base.entity.APIRequest;
import com.tc.base.entity.APIResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.util.List;
/**
 * 流程模型控制器
 */
@Api(value = "流程模型控制器", tags = "流程模型控制器")
@Controller
@RequestMapping(value = "/bpmn/workflow/model")
public class ModelController2 {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected RepositoryService repositoryService;

    /**
     * 模型列表
     */
    @ApiOperation(value = "模型列表", notes = "模型列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public APIResult modelList(@RequestBody APIRequest request) {
        APIResult result = new APIResult<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            int[] pageParams = PageUtil.init(pageNo, pageSize);
            List<Model> list = repositoryService.createModelQuery().listPage(pageParams[0], pageParams[1]);
            result.setData(list);
            result.setMessage("查询模型列表成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/workflow/model/list", e);
        }
        return result;
    }

    /**
     * 创建模型
     */
    @ApiOperation(value = "创建模型", notes = "创建模型")
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public void create(@RequestParam("name") String name, @RequestParam("key") String
            key, @RequestParam("description") String description,
                       HttpServletRequest request, HttpServletResponse response) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();
            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));
            Model model = repositoryService.getModel(key);
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        } catch (Exception e) {
            logger.error("/bpmn/workflow/model/create/", e);
        }
    }

    /**
     * 根据Model部署流程
     */
    @ApiOperation(value = "根据modelId部署流程", notes = "根据modelId部署流程")
    @RequestMapping(value = "/deploy/{modelId}", method = RequestMethod.GET)
    @ResponseBody
    public APIResult deploy(@PathVariable("modelId") String modelId) {
        APIResult result = new APIResult<>();
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).
                    addString(processName, new String(bpmnBytes, "utf-8")).deploy();
            result.setMessage("部署成功，部署ID=" + deployment.getId());
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/workflow/model/deploy/" + modelId, e);
        }
        return result;
    }

    /**
     * 导出model对象为指定类型
     *
     * @param modelId 模型ID
     * @param type    导出文件类型(bpmn\json)
     */
    @ApiOperation(value = "导出model对象为指定类型", notes = "导出model对象为指定类型")
    @RequestMapping(value = "export/{modelId}/{type}", method = RequestMethod.GET)
    public void export(@PathVariable("modelId") String modelId,
                       @PathVariable("type") String type,
                       HttpServletResponse response) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());
            JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            // 处理异常
            if (bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can't export for type: " + type);
                response.flushBuffer();
                return;
            }
            String filename = "";
            byte[] exportBytes = null;
            String mainProcessId = bpmnModel.getMainProcess().getId();
            if (type.equals("bpmn")) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                exportBytes = xmlConverter.convertToXML(bpmnModel);
                filename = mainProcessId + ".bpmn20.xml";
            } else if (type.equals("json")) {

                exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";
            }
            ByteArrayInputStream in = new ByteArrayInputStream(exportBytes);
            IOUtils.copy(in, response.getOutputStream());
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("导出model的xml文件失败：modelId={}, type={}", modelId, type, e);
        }
    }

    @ApiOperation(value = "根据modelId删除流程", notes = "根据modelId删除流程")
    @RequestMapping(value = "/delete/{modelId}", method = RequestMethod.DELETE)
    @ResponseBody
    public APIResult delete(@PathVariable("modelId") String modelId) {
        APIResult result = new APIResult<>();
        try {
            repositoryService.deleteModel(modelId);
            result.setMessage("删除流程成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/workflow/model/delete/" + modelId, e);
        }
        return result;
    }

}
